package com.example.module_home.viewmodel

import androidx.lifecycle.viewModelScope
import com.example.lib_mvicore.viewmodel.BaseViewModel
import com.example.module_home.intent.SimpleTypeIntent
import com.example.module_home.model.service.VideoTypeService
import com.example.module_home.state.SimpleTypeState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2024/10/28
 */
class SimpleTypeViewModel:BaseViewModel<SimpleTypeIntent> (){
    private val service:VideoTypeService by  lazy { VideoTypeService() }

    private var simpleTypeFlow = MutableStateFlow<SimpleTypeState>(SimpleTypeState.Init)
    val simpleTypeFlow_ = simpleTypeFlow.asStateFlow()

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SimpleTypeIntent.getSimpleType-> getSimpleTypeData()
                }
            }
        }
    }

    private fun getSimpleTypeData() {
        viewModelScope.launch {
            flow {
                emit(service.getSimpleType())
            }.catch { e->
                simpleTypeFlow.value = SimpleTypeState.Failed(e.message.toString())
            }.filter {
                it != null
            }.collect{
                if(it.code == 0){
                    if(it.data.isEmpty()){
                        simpleTypeFlow.value = SimpleTypeState.Empty
                    }else{
                        simpleTypeFlow.value = SimpleTypeState.SimpleTypeSuccess(it.data)
                    }
                }else{
                    simpleTypeFlow.value = SimpleTypeState.Failed(it.msg)
                }
            }

        }
    }
}